from app.db.mongoClient import ErrMongoClient, get_mongo_client
from . import dbSynPosBill, collectionBillList
from datetime import datetime
from app.db.dbDiningQuery import queryDiningName, queryAllDiningNoById
from app.db.dbStallQuery import queryStallName 
from app.db.dbStallQuery import queryStallIds
from app.globals.publicMethod import getTodayLastDate, getTodayZeroDate, globalTimeCompare
from app.globals.publicMethod import globalTimeToString

def queryAllReport(diningNo, start_time, end_time):
    '''
    餐厅全部档口消费汇总报表
    '''
    try:
        mg_client = get_mongo_client()
        start = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        reportList = []
        collection = mg_client[dbSynPosBill][collectionBillList]
        # 查询所有档口Id 
        res = queryStallIds(diningNo)
        if res is False:
            return reportList

        for n, v in enumerate(res):
            stallId = v
            # 初始化数量
            breakfastCount = 0
            breakfastMoney = 0
            lunchCount = 0
            lunchMoney = 0
            dinnerCount = 0
            dinnerMoney = 0
            snackCount = 0
            snackMoney = 0

            # $gte表示开始时间  $lte表示结束时间  
            '''
            a) 查询开始时间大于start并且 结束时间小于end  ， mealName = 餐次名的文档记录
            b) 并对 mealName字段进行分组，并计算mealName字段相同值的总和
            c) $match 筛选操作符 值为需要筛选的内容
            '''
            # 查询早餐的单数
            cursorcount = collection.aggregate(
                [
                    {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallId,  "mealName": "早餐", 'billState': '1'}},
                    {"$group": {"_id": "$mealName", "totalCount": {"$sum": 1}}}
                ]
            )
            
            for res in cursorcount:
                breakfastCount = res.get('totalCount')

            # 查询早餐的钱数
            cursorcount = collection.aggregate(
                [
                    {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallId,  "mealName": "早餐", 'billState': '1'}},
                    {"$group": {"_id": "money", "totalMoney": {"$sum":"$chargeAmount"}}}
                ]
            )
            
            for res in cursorcount:
                breakfastMoney = res.get('totalMoney')

            # 查询午餐的单数
            cursorcount = collection.aggregate(
                [
                    {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallId,  "mealName": "午餐", 'billState': '1'}},
                    {"$group": {"_id": "$mealName", "totalCount": {"$sum": 1}}}
                ]
            )
            
            for res in cursorcount:
                lunchCount = res.get('totalCount')

            # 查询午餐的钱数
            cursorcount = collection.aggregate(
                [
                    {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallId,  "mealName": "午餐", 'billState': '1'}},
                    {"$group": {"_id": "money", "totalMoney": {"$sum":"$chargeAmount"}}}
                ]
            )
            
            for res in cursorcount:
                lunchMoney = res.get('totalMoney')

            # 查询晚餐的单数
            cursorcount = collection.aggregate(
                [
                    {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallId,  "mealName": "晚餐", 'billState': '1'}},
                    {"$group": {"_id": "$mealName", "totalCount": {"$sum": 1}}}
                ]
            )
            
            for res in cursorcount:
                dinnerCount = res.get('totalCount')

            # 查询晚餐的钱数
            cursorcount = collection.aggregate(
                [
                    {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallId,  "mealName": "晚餐", 'billState': '1'}},
                    {"$group": {"_id": "money", "totalMoney": {"$sum":"$chargeAmount"}}}
                ]
            )
            
            for res in cursorcount:
                dinnerMoney = res.get('totalMoney')

            # 查询夜宵的单数
            cursorcount = collection.aggregate(
                [
                    {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallId,  "mealName": "夜宵", 'billState': '1'}},
                    {"$group": {"_id": "$mealName", "totalCount": {"$sum": 1}}}
                ]
            )
            
            for res in cursorcount:
                snackCount = res.get('totalCount')

            # 查询夜宵的钱数
            cursorcount = collection.aggregate(
                [
                    {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallId,  "mealName": "夜宵", 'billState': '1'}},
                    {"$group": {"_id": "money", "totalMoney": {"$sum":"$chargeAmount"}}}
                ]
            )
            
            for res in cursorcount:
                snackMoney = res.get('totalMoney')

            report = {
                'diningName': queryDiningName(diningNo),
                'stallName': queryStallName(stallId),
                'todayTotalCount': breakfastCount + lunchCount + dinnerCount + snackCount,
                'todayTotalMoney': breakfastMoney + lunchMoney + dinnerMoney + snackMoney,
                'breakfastCount': breakfastCount,
                'breakfastMoney': breakfastMoney,
                'lunchCount': lunchCount,
                'lunchMoney': lunchMoney,
                'dinnerCount': dinnerCount,
                'dinnerMoney': dinnerMoney,
                'snackCount': snackCount,
                'snackMoney': snackMoney
            }
            reportList.append(report)
                 
        return reportList 
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryReport(diningNo, stallNo, start_time, end_time):
    '''
    餐厅某个档口消费汇总报表
    '''
    try:
        mg_client = get_mongo_client()
        start = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        reportList = []
        collection = mg_client[dbSynPosBill][collectionBillList]

        # 初始化数量
        breakfastCount = 0
        breakfastMoney = 0
        lunchCount = 0
        lunchMoney = 0
        dinnerCount = 0
        dinnerMoney = 0
        snackCount = 0
        snackMoney = 0

        # $gte表示开始时间  $lte表示结束时间  
        '''
        a) 查询开始时间大于start并且 结束时间小于end  ， mealName = 餐次名的文档记录
        b) 并对 mealName字段进行分组，并计算mealName字段相同值的总和
        c) $match 筛选操作符 值为需要筛选的内容
        '''
        # 查询早餐的单数
        cursorcount = collection.aggregate(
            [
                {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallNo,  "mealName": "早餐", 'billState': '1'}},
                {"$group": {"_id": "$mealName", "totalCount": {"$sum": 1}}}
            ]
        )
        
        for res in cursorcount:
            breakfastCount = res.get('totalCount')

        # 查询早餐的钱数
        cursorcount = collection.aggregate(
            [
                {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallNo,  "mealName": "早餐", 'billState': '1'}},
                {"$group": {"_id": "money", "totalMoney": {"$sum":"$chargeAmount"}}}
            ]
        )
        
        for res in cursorcount:
            breakfastMoney = res.get('totalMoney')

        # 查询午餐的单数
        cursorcount = collection.aggregate(
            [
                {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallNo,  "mealName": "午餐", 'billState': '1'}},
                {"$group": {"_id": "$mealName", "totalCount": {"$sum": 1}}}
            ]
        )
        
        for res in cursorcount:
            lunchCount = res.get('totalCount')

        # 查询午餐的钱数
        cursorcount = collection.aggregate(
            [
                {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallNo,  "mealName": "午餐", 'billState': '1'}},
                {"$group": {"_id": "money", "totalMoney": {"$sum":"$chargeAmount"}}}
            ]
        )
        
        for res in cursorcount:
            lunchMoney = res.get('totalMoney')

        # 查询晚餐的单数
        cursorcount = collection.aggregate(
            [
                {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallNo,  "mealName": "晚餐", 'billState': '1'}},
                {"$group": {"_id": "$mealName", "totalCount": {"$sum": 1}}}
            ]
        )
        
        for res in cursorcount:
            dinnerCount = res.get('totalCount')

        # 查询晚餐的钱数
        cursorcount = collection.aggregate(
            [
                {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallNo,  "mealName": "晚餐", 'billState': '1'}},
                {"$group": {"_id": "money", "totalMoney": {"$sum":"$chargeAmount"}}}
            ]
        )
        
        for res in cursorcount:
            dinnerMoney = res.get('totalMoney')

        # 查询夜宵的单数
        cursorcount = collection.aggregate(
            [
                {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallNo,  "mealName": "夜宵", 'billState': '1'}},
                {"$group": {"_id": "$mealName", "totalCount": {"$sum": 1}}}
            ]
        )
        
        for res in cursorcount:
            snackCount = res.get('totalCount')

        # 查询夜宵的钱数
        cursorcount = collection.aggregate(
            [
                {"$match": {"skj130OrderTime": {'$gte':start,'$lte':end }, "diningNo": diningNo, "stallNo": stallNo,  "mealName": "夜宵", 'billState': '1'}},
                {"$group": {"_id": "money", "totalMoney": {"$sum":"$chargeAmount"}}}
            ]
        )
        
        for res in cursorcount:
            snackMoney = res.get('totalMoney')

        report = {
            'diningName': queryDiningName(diningNo),
            'stallName': queryStallName(stallNo),
            'todayTotalCount': breakfastCount + lunchCount + dinnerCount + snackCount,
            'todayTotalMoney': breakfastMoney + lunchMoney + dinnerMoney + snackMoney,
            'breakfastCount': breakfastCount,
            'breakfastMoney': breakfastMoney,
            'lunchCount': lunchCount,
            'lunchMoney': lunchMoney,
            'dinnerCount': dinnerCount,
            'dinnerMoney': dinnerMoney,
            'snackCount': snackCount,
            'snackMoney': snackMoney
        }
        reportList.append(report)
                 
        return reportList 
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryOrder(diningNo, stallNo, start_time, end_time, bill_state, pay_type, m_from, m_count):
    '''
    餐厅档口消费明细报表
    '''
    try:
        mg_client = get_mongo_client()
        start = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        orderList = []
        # 1000表示全部 
        if bill_state != 1000 and pay_type == 1000:
            # $gte表示开始时间  $lte表示结束时间  
            res = mg_client[dbSynPosBill][collectionBillList].find({'skj130OrderTime':{'$gte':start,'$lte':end }, 'diningNo': diningNo, 'stallNo': stallNo, 'billState': bill_state}).limit(m_count).skip(m_from)
            for v in res:
                order = {
                    'billId': v.get('billId'),
                    'thirdOrderNo': v.get('thirdOrderNo'),
                    'deviceNo': v.get('deviceNo'),
                    'diningName': queryDiningName(diningNo),
                    'stallName': queryStallName(stallNo),
                    'mealName': v.get('mealName'),
                    'chargeAmount': v.get('chargeAmount'),
                    'account': v.get('account'),
                    'billState': v.get('billState'),
                    'payType': v.get('payType'),
                    'dishList': v.get('dishList')
                }
                orderList.append(order)
        elif bill_state == 1000 and pay_type != 1000:
            res = mg_client[dbSynPosBill][collectionBillList].find({'skj130OrderTime':{'$gte':start,'$lte':end }, 'diningNo': diningNo, 'stallNo': stallNo, 'payType': pay_type}).limit(m_count).skip(m_from)
            for v in res:
                order = {
                    'billId': v.get('billId'),
                    'thirdOrderNo': v.get('thirdOrderNo'),
                    'deviceNo': v.get('deviceNo'),
                    'diningName': queryDiningName(diningNo),
                    'stallName': queryStallName(stallNo),
                    'mealName': v.get('mealName'),
                    'chargeAmount': v.get('chargeAmount'),
                    'account': v.get('account'),
                    'billState': v.get('billState'),
                    'payType': v.get('payType'),
                    'dishList': v.get('dishList')
                }
                orderList.append(order)
        elif bill_state == 1000 and pay_type == 1000:
            res = mg_client[dbSynPosBill][collectionBillList].find({'skj130OrderTime':{'$gte':start,'$lte':end }, 'diningNo': diningNo, 'stallNo': stallNo}).limit(m_count).skip(m_from)
            for v in res:
                order = {
                    'billId': v.get('billId'),
                    'thirdOrderNo': v.get('thirdOrderNo'),
                    'deviceNo': v.get('deviceNo'),
                    'diningName': queryDiningName(diningNo),
                    'stallName': queryStallName(stallNo),
                    'mealName': v.get('mealName'),
                    'chargeAmount': v.get('chargeAmount'),
                    'account': v.get('account'),
                    'billState': v.get('billState'),
                    'payType': v.get('payType'),
                    'dishList': v.get('dishList')
                }
                orderList.append(order)
        else:
            res = mg_client[dbSynPosBill][collectionBillList].find({'skj130OrderTime':{'$gte':start,'$lte':end }, 'diningNo': diningNo, 'stallNo': stallNo, 'billState': bill_state, 'payType': pay_type}).limit(m_count).skip(m_from)
            for v in res:
                order = {
                    'billId': v.get('billId'),
                    'thirdOrderNo': v.get('thirdOrderNo'),
                    'deviceNo': v.get('deviceNo'),
                    'diningName': queryDiningName(diningNo),
                    'stallName': queryStallName(stallNo),
                    'mealName': v.get('mealName'),
                    'chargeAmount': v.get('chargeAmount'),
                    'account': v.get('account'),
                    'billState': v.get('billState'),
                    'payType': v.get('payType'),
                    'dishList': v.get('dishList')
                }
                orderList.append(order)
            
        return orderList 
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryAmountBillCount_someDay(diningNo, stallNo, start_time, end_time, deviceNo):
    '''
    查询每天的统计信息
    '''
    try:
        mg_client = get_mongo_client()
        start = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        data = {}
        dish_name_count_list = []
        sub_amount_and_count_list = []
        collection = mg_client[dbSynPosBill][collectionBillList]
        match_dict = {
            "$match": {
                'skj130OrderTime': {
                    '$gte': start,
                    '$lte': end
                },
                'diningNo': diningNo,
                'stallNo': stallNo,
                'deviceNo': deviceNo,
                'billState': 1
            }
        }
        unwind_dict = {'$unwind': "$dishList"}
        group_dict = {
            '$group': {
                '_id': {'Id': '$dishList.dishId'},
                'dishTotalCount': {
                    '$sum': '$dishList.dishCount'
                },
                'dishName': {
                    '$addToSet': '$dishList.dishName'
                },
                'dishPrice': {
                    '$addToSet': '$dishList.dishPrice'
                },
                'dishUnit': {
                    '$addToSet': '$dishList.dishUnit'
                }
            }
        }
        sort_dict = {'$sort': {'dishTotalCount': -1}}
        project_dict = {
            '$project': {
                '_id': 0,
                'dishId': '$_id.Id',
                'dishCount': '$dishTotalCount',
                'dishName': '$dishName',
                'dishPrice': '$dishPrice',
                'dishUnit': '$dishUnit'
            }
        }
        cursorcount = collection.aggregate([match_dict, unwind_dict, group_dict, sort_dict, project_dict])
        for v in cursorcount:
            #print('----------------------', v)
            one_dishCount = {
                'dish_count': v.get('dishCount'),
                'dish_name': v.get('dishName')[0],
                'dish_price': v.get('dishPrice')[0],
                'dish_unit': v.get('dishUnit')[0]
            }
            dish_name_count_list.append(one_dishCount)

        group_dict = {
            '$group': {
                '_id': '$diningNo', 
                'total_bill_count': {
                    '$sum': 1
                },
                'total_amount_count': {
                    '$sum': '$chargeAmount'
                },
                'consum_of_person': {
                    '$avg': '$chargeAmount'
                }
            }
        }
        cursorcount = collection.aggregate([match_dict, group_dict])
        for v in cursorcount:
            #print('----------------------', v)
            data['consum_of_person'] = int(v.get('consum_of_person'))
            data['total_amount_count'] = v.get('total_amount_count')
            data['total_bill_count'] = v.get('total_bill_count')
        
        # 对时间进行升序
        TimeSort = {
            '$sort': {'_id' : 1}
        }
        # 如果要按天统计数据
        if globalTimeCompare(start_time, end_time) == 'day':
            sub_amount_dict = {
                '$group': {
                    '_id': {"$dateToString":{'format':'%m-%d','date':'$skj130OrderTime'}}, 
                    'count': {'$sum': 1}, 
                    'Totalmoney': {'$sum': '$chargeAmount'}
                }
            } 
            cursorcount = collection.aggregate([match_dict, sub_amount_dict, TimeSort])
            for v in cursorcount:
                one_dishCount = {
                    'amount_count': v.get('Totalmoney'),
                    'bill_count': v.get('count'),
                    'current_time': v.get('_id')
                }
                sub_amount_and_count_list.append(one_dishCount)
            data['sub_amount_and_count_type'] = 'day'
        # 如果要按小时统计数据
        else:
            sub_amount_dict = {
                '$group': {
                    '_id': {"$dateToString":{'format':'%H:','date':'$skj130OrderTime'}}, 
                    'count': {'$sum': 1}, 
                    'Totalmoney': {'$sum': '$chargeAmount'}
                }
            } 
            cursorcount = collection.aggregate([match_dict, sub_amount_dict, TimeSort])
            for v in cursorcount:
                one_dishCount = {
                    'amount_count': v.get('Totalmoney'),
                    'bill_count': v.get('count'),
                    'current_time': v.get('_id') + '00'
                }
                sub_amount_and_count_list.append(one_dishCount)
            data['sub_amount_and_count_type'] = 'hour'    
        
        data['dish_name_count_list'] = dish_name_count_list
        data['sub_amount_and_count_list'] = sub_amount_and_count_list
        
        return data
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def queryMealDayCount(diningNo, stallNo, deviceNo):
    '''
    查询当餐/当天份数金额
    '''
    try:
        mg_client = get_mongo_client()
        collection = mg_client[dbSynPosBill][collectionBillList]
        day_amountCount = 0
        day_billCount = 0
        meal_amountCount = 0
        meal_billCount = 0

        # 查询当天的数据
        match_dict = {
            "$match": {
                'skj130OrderTime': {
                    '$gte': getTodayZeroDate(),
                    '$lte': getTodayLastDate()
                },
                'diningNo': diningNo,
                'stallNo': stallNo,
                'deviceNo': deviceNo,
                'billState': 1
            }
        }
        group_dict = {
            '$group': {
                '_id': {'Id': '$diningNo'},
                'total_bill_count': {
                    '$sum': 1
                },
                'total_amount_count': {
                    '$sum': '$chargeAmount'
                }
            }
        }
        cursorcount = collection.aggregate([match_dict, group_dict])
        for v in cursorcount:
            day_amountCount = int(v.get('total_amount_count'))
            day_billCount = int(v.get('total_bill_count'))
        
        # 查询当餐的数据
        start, end = queryAllDiningNoById(diningNo)
        
        # 当前时间属于数据库中餐次的时间段的时候
        if start != '' and end != '': 
            match_dict_sec = {
                "$match": {
                    'skj130OrderTime': {
                        '$gte': start,
                        '$lte': end
                    },
                    'diningNo': diningNo,
                    'stallNo': stallNo,
                    'deviceNo': deviceNo,
                    'billState': 1
                }
            }
            group_dict_sec = {
                '$group': {
                    '_id': {'Id': '$diningNo'},
                    'total_bill_count': {
                        '$sum': 1
                    },
                    'total_amount_count': {
                        '$sum': '$chargeAmount'
                    }
                }
            }
            cursorcount = collection.aggregate([match_dict_sec, group_dict_sec])
            for v in cursorcount:
                meal_amountCount = int(v.get('total_amount_count'))
                meal_billCount = int(v.get('total_bill_count'))
            
        info = {
            'day_amountCount': day_amountCount,
            'day_billCount': day_billCount,
            'meal_amountCount': meal_amountCount,
            'meal_billCount': meal_billCount
        }

        return info
    except Exception as e:
        raise ErrMongoClient.data(str(e))
    
    
def query_note_order(billId):
    '''
     获取小票打印内容
    '''
    try:
        mg_client = get_mongo_client()
        cond = {'billId': billId}
        v = mg_client[dbSynPosBill][collectionBillList].find_one(cond)
        data = {}
        if v is None:
            return None

        dishList = v.get('dishList') 
        outList = []
        count = 0
        if dishList is not None and len(dishList) > 0 :
            for s in dishList:
                info = {
                    'dishCount': s.get('dishCount'),
                    'dishName':  s.get('dishName'),
                    'dishPrice': s.get('dishPrice'),
                    'dishUnit': s.get('dishUnit')
                }
                count = count + s.get('dishCount')
                outList.append(info)
                
        data = {
            'billId': billId,
            'thirdOrderNo': v.get('thirdOrderNo'),
            'orderAmount': v.get('orderAmount'),
            'chargeAmount': v.get('chargeAmount'),
            'payType': v.get('payType'),
            'orderTime': globalTimeToString(v.get('skj130OrderTime')),
            'stallName': queryStallName(v.get('stallNo')),
            'totalCount': count,
            'dishList': outList
        }

        return data 
    except Exception as e:
        raise ErrMongoClient.data(str(e))